package com.zyf.chapter02.behavior.iterator.snapshot;

/**
 * 解决方案一：复制一份数组，当做快照版本，好在是浅拷贝，所以不会有额外的内存开销
 * @author yifeng
 */
public class SnapshotArrayIterator<E> implements Iterator<E>{

    ArrayList<E> snapshotList;

    int cursor;

    public SnapshotArrayIterator(List<E> list) {
        snapshotList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            snapshotList.add(list.get(i));
        }
    }

    @Override
    public boolean hasNext() {
        return cursor < snapshotList.size();
    }

    @Override
    public void next() {
        cursor++;
    }

    @Override
    public E currentItem() {
        return snapshotList.get(cursor);
    }

    @Override
    public String toString() {
        return "SnapshotArrayIterator{" +
                "snapshotList=" + snapshotList +
                '}';
    }

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);

        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.currentItem() + ", ");
            iterator.next();
        }
        list.remove(4);
        System.out.println();
        Iterator iterator2 = list.iterator();
        while (iterator2.hasNext()) {
            System.out.print(iterator2.currentItem() + ", ");
            iterator2.next();
        }
    }
}
